package com.zhida.jiyangcenter.order.fragment

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.flyco.animation.BounceEnter.BounceTopEnter
import com.flyco.animation.SlideExit.SlideBottomExit
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.google.gson.Gson
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.dialog.ExpressDialog
import com.zhida.jiyangcenter.mian.BaseFragment
import com.zhida.jiyangcenter.order.CommentOrderActivity
import com.zhida.jiyangcenter.order.PayOrderActivity
import com.zhida.jiyangcenter.order.ServeOrderDetailsActivity
import com.zhida.jiyangcenter.order.ShopOrderActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@ContentLayout(R.layout.list)
class ServeOrderFragment(val type: Int) : BaseFragment() {
    override fun getTitle(): CharSequence {
        return when (type) {
            -1 -> "全部"
            3 -> "已使用"
            2 -> "待服务"
//            5 -> "退款/售后"
            else -> "未知"
        }
    }

    var page = 1
    val adapter = Adapter()
    private lateinit var loadService: LoadService<*>
    override fun initConfig(savedInstanceState: Bundle?) {
        loadService = LoadUtils.getDefault().register(refresh_layout) {
            page = 1
            getData()
        }
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(requireContext())
                .sizeResId(R.dimen.dividerBig).colorResId(R.color.colorBack).build()
        )
        recycler_view.adapter = adapter
        refresh_layout.setOnRefreshListener {
            page = 1
            getData()
        }
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, recycler_view)
        adapter.setOnItemClickListener { _, view, position ->
            startActivity<ServeOrderDetailsActivity> {
                putExtra("uuid", adapter.data[position].order_uuid)
            }
        }
        adapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.btn_wuliu -> {
                    when (adapter.data[position].state) {
                        "0" -> {
                            val dialog = NormalDialog(context)
                            dialog.content("是否取消服务订单？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("温馨提示")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                cancel(adapter.data[position].order_uuid ?: "")
                            })
                        }
                        else -> {
                            val dialog = NormalDialog(context)
                            dialog.content("您的服务还未体验，是否确认退款？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("退款")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                refundOrder(adapter.data[position].order_uuid ?: "")
                            })
                        }
                    }

                }
                R.id.btn_operate -> {
                    when (adapter.data[position].state) {
                        "0" -> {
                            startActivity<PayOrderActivity> {
                                putExtra("orderCode", adapter.data[position]?.order_uuid)
                                putExtra("total_money", adapter.data[position].actual_payment)
                                putExtra("kind", "4")
                            }
                        }
                        "2" -> {
                            lifecycleScope.request({
                                APIAccount.service()
                                    .serveCode(adapter.data[position].order_uuid ?: "")
                            }, object : BaseAPI<ServeCodeEntity>() {
                                override fun onSuccess(
                                    t: ServeCodeEntity?,
                                    state: Int,
                                    msg: String
                                ) {
                                    val dialog = NormalDialog(context)
                                    dialog.content("您的服务码是：${t?.serve_code}")
                                        .style(NormalDialog.STYLE_TWO)//
                                        .title("查看服务码")
                                        .btnNum(1)
                                        .btnTextColor(
                                            resColor(R.color.colorAccent)
                                        )
                                        .btnText("我已知晓")
                                        .titleTextSize(23f)
                                        .showAnim(BounceTopEnter())
                                        .dismissAnim(SlideBottomExit())
                                        .show()

                                    dialog.setOnBtnClickL(OnBtnClickL {
                                        dialog.dismiss()
                                    })
                                }

                                override fun onError(e: APIException) {
                                    tipFail(e.eMessage)
                                }

                            })

                        }
                        "3" -> {
                            startActivity<CommentOrderActivity> {
                                putExtra("type", "2")
                                putExtra("uuid", adapter.data[position].order_uuid)
                            }
                        }
                        "7" -> {
                            val dialog = NormalDialog(context)
                            dialog.content("请确保您已体验完成服务，是否确认完成？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("温馨提示")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                receivingOrder(adapter.data[position].order_uuid ?: "")
                            })
                        }
                    }
                }
            }
        }
        getData()
    }

    private fun cancel(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().serveOrderCancel(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    page = 1
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun receivingOrder(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().serveOrderReceiving(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    page = 1
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun refundOrder(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().serveOrderRefund(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    page = 1
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun getData() {
        lifecycleScope.request(
            { APIAccount.service().serveOrderList(page, type) },
            object : BaseAPI<ServeOrderListEntity>() {
                override fun onSuccess(t: ServeOrderListEntity?, state: Int, msg: String) {
                    if (t != null && !t.orders?.order.isNullOrEmpty()) {
                        if (page <= 1) {
                            adapter.setNewData(t.orders?.order)
                            loadService.showSuccess()
                            refresh_layout.finishRefresh()
                            if (t.orders?.order!!.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            }
                        } else {
                            adapter.addData(t.orders?.order!!)
                            if (t.orders.order.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            } else adapter.loadMoreComplete()
                        }
                    } else onError(APIException(APIException.Type.EMPTY))
                }

                override fun onError(e: APIException) {
                    if (page <= 1) when (e.type) {
                        APIException.Type.EMPTY -> loadService.showCallback(
                            EmptyCallback::class,
                            "暂无服务订单"
                        )
                        APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                        else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                    } else when (e.type) {
                        APIException.Type.EMPTY -> {
                            adapter.loadMoreFail()
                        }
                        else -> adapter.loadMoreFail()
                    }
                }

            })
    }

    class Adapter :
        BaseQuickAdapter<ServeOrderListEntity.Orders.Order, BaseViewHolder>(R.layout.item_serve_order) {
        override fun convert(helper: BaseViewHolder, item: ServeOrderListEntity.Orders.Order?) {
            glideImage(helper.getView(R.id.niv_item_buy_car), item?.serve?.picture ?: "")
            helper.setText(R.id.tv_item_buy_car_name, item?.serve?.serve_name)
                .setText(R.id.tv_item_buy_car_money, "￥${item?.serve?.price}")
                .setText(R.id.tv_item_num, "x${item?.serve?.total_num}")
                .setText(R.id.tv_buy_car_name, item?.serve?.store_name)
            when (item?.state) {
                "0" -> {
                    helper.setGone(R.id.btn_wuliu, true).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_wuliu, "取消")
                        .setText(R.id.btn_operate, "去支付").setText(R.id.tv_order_type, "待支付")
                }
                "1" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "已取消")
                }
                "2" -> {
                    helper.setGone(R.id.btn_wuliu, true).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_operate, "查看服务码")
                        .setText(R.id.tv_order_type, "待服务")
                }
                "3" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_operate, "去评价")
                        .setText(R.id.tv_order_type, "待评价")
                }
                "4" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "已完成")
                }
                "5" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "待退款服务")
                }
                "6" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "已退款服务")
                }
                "7" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_operate, "确认服务完成")
                        .setText(R.id.tv_order_type, "已开始服务")
                }
            }
            helper.setText(
                R.id.tv_shop_order_money,
                "剩余次数：¥${item?.serve?.num}"
            )
                .addOnClickListener(R.id.btn_operate).addOnClickListener(R.id.btn_wuliu)
        }

    }
}